package com.yuan.blog.service.impl;

import com.yuan.blog.constants.RedisKey;
import com.yuan.blog.dto.UserToken;
import com.yuan.blog.entity.SystemUser;
import com.yuan.blog.exception.BaseException;
import com.yuan.blog.exception.UserNotFoundException;
import com.yuan.blog.security.UserTokenThreadLocal;
import com.yuan.blog.service.ISysLoginService;
import com.yuan.blog.service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @program: blog-system
 * @description:
 * @author: yuan_boss
 * @create: 2022-12-28 14:36
 **/
@Service
public class SysLoginServiceImpl implements ISysLoginService {

    @Autowired
    private ISystemUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(String username, String password) {

        //判断账号是否存在
        SystemUser user = userService.getByUserName(username);
        if (user == null){
            throw new UserNotFoundException(101,"用户名不存在");
        }

        //检查密码
        if (!password.equals(user.getPassword())){
            throw new BaseException(101,"用户名或者密码错误");
        }

        //创建Token对象
        UserToken token = tokenService.createToken(user);

        return token.getToken();
    }

    @Override
    public void logout() {
        String token = String.format(RedisKey.USER_LOGIN_KEY, UserTokenThreadLocal.get().getToken());
        stringRedisTemplate.delete(token);
    }
}
